package com.pine.dbant.core.config;


import com.pine.dbant.common.exeception.BusinessException;
import com.pine.sunflower.core.model.CommonErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 错误处理拦截器
 *
 * @author xiaoyuan
 * @create 2022/4/15 16:04
 **/
@Slf4j
@Order(1)
@Configuration
public class ErrorInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("--- 开始执行错误拦截器 ---");
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (status != null) {
            Object exception = request.getAttribute("org.springframework.boot.web.servlet.error.DefaultErrorAttributes.ERROR");
            if (exception instanceof Exception) {
                log.error("请求发生错误",(Exception)exception);
            }
            String url = request.getRequestURI();
            Integer state = Integer.valueOf(String.valueOf(status));
            switch (state) {
                case 404:
                    url = String.valueOf(request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI));
                case 405:
                    log.debug("该错误请求uri:{}，method:{}", url, request.getMethod());
                    throw new BusinessException(CommonErrorCode.REQUEST_ERROR.getDescription());
                default:
                    throw new BusinessException(CommonErrorCode.SYSTEM_ERROR.getDescription());
            }
        }
        return true;
    }
}
